package cn.lzy.ioc;

import cn.lzy.ioc.entity.Cat;
import cn.lzy.ioc.entity.Dog;
import cn.lzy.ioc.framework.BeanDefinition;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author Administrator
 * @Date 2023/8/30 15:23
 * @Version
 **/
public class TestDemo {

    public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        // 1.创建一个容器（模拟 Spring 容器）
        Map<String, Object> container = new HashMap<String, Object>();

        // 2.加载资源文件（beans.json）的 bean
        InputStream inputStream = TestDemo.class.getResourceAsStream("/beans.json");
        ObjectMapper objectMapper = new ObjectMapper();
        List<BeanDefinition> beanDefinitionList = objectMapper.readValue(inputStream, new TypeReference<List<BeanDefinition>>() {
        });

        // 3.将加载的bean存到容器中
        for (BeanDefinition bd : beanDefinitionList) {
            String clazz = bd.getClazz();
            String id = bd.getId();
            // 根据类的全路径，生成实例对象
            Object instance = Class.forName(clazz).newInstance();
            container.put(id, instance);
        }
        System.err.println("容器内存在的bean：" +container);

        // 4.获取容器内指定的bean
        Dog dog = (Dog) container.get("dog");
        System.out.println(dog);
        Cat cat = (Cat) container.get("cat");
        System.out.println(cat);
    }
}
